package keeto.com.vn.classified.ui;

import java.util.ArrayList;

import keeto.com.vn.classfied.model.Area;
import keeto.com.vn.classified.adapter.AdapterProductViewAll;
import keeto.com.vn.classified.adapter.ProductsAdapter;
import keeto.com.vn.classified.core.ClassifiedCore;
import keeto.com.vn.classified.core.ClassifiedListener;
import keeto.com.vn.classified.database.BuiltinService;
import keeto.com.vn.classified.database.BuiltinServiceManager;
import keeto.com.vn.classified.manager.IAManager;
import keeto.com.vn.classified.network.IProtocol;
import keeto.com.vn.classified.network.entity.ListItemEntity;
import keeto.com.vn.classified.utils.StatusMessageUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.util.AQUtility;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;


public class ProductsActivity extends Activity implements OnItemClickListener, OnRefreshListener<ListView>, OnClickListener {

	private final static String ACTION_PRODUCT_SEARCH_GLOBAL = "Search_GloBal";
	private final static String ACTION_PRODUCT_SEARCH_GLOBAL_BY_KEY = "Search_GloBal_By_Key";

	private final static String ACTION_PRODUCT_CATEGORY_SEARCH = "ProductSearchCategory";
	private final static String EXTRA_KEY_WORD_SEARCH = "KeyWord";
	private final static String EXTRA_CATEGORY_ID = "CategoryId";
	public final static int REQUEST_SEARCH = 1;


	private ImageButton btnBack;
	private ImageButton btnHome;
	private ImageView btnSearch;
	private ProgressBar mBar;

	private BuiltinServiceManager mBuiltinServiceManager = null;
	private  BuiltinService builtservice = null;
	private PullToRefreshListView mLisview;
	private AdapterProductViewAll mAdapter = null;
	private EditText edt_search;

	private SearchListener mListener = new SearchListener();
	private static InUIThreadHandler mReturnCodeHandler = null;
	private Bundle extras;	
	private String Action;
	private String keyWord;
	private Area mArea ;
	private final int PAGELIMIT= 10;
	private int PageNumber = 1;
	private final int ISDISABLE = 0;
	private String CategoryType = "products";
	private String CategoryId = null;
	private AQuery mQuery;

	private ArrayList<ListItemEntity> mList = new ArrayList<ListItemEntity>();

	public static void actionSearchGlobal(Context context) {
		Intent i = new Intent(context, ProductsActivity.class);
		i.setAction(ACTION_PRODUCT_SEARCH_GLOBAL);
		context.startActivity(i);
	}
	public static void actionSearchGlobalbyKey(Context context, String keyword) {
		Intent i = new Intent(context, ProductsActivity.class);
		i.setAction(ACTION_PRODUCT_SEARCH_GLOBAL_BY_KEY);
		i.putExtra(EXTRA_KEY_WORD_SEARCH, keyword);
		context.startActivity(i);
	}
	public static void actionSearchByCategory(Activity context,
			String categoryId, String keywordSearch) {
		Intent i = new Intent(context, ProductsActivity.class);
		i.setAction(ACTION_PRODUCT_CATEGORY_SEARCH);
		i.putExtra(EXTRA_CATEGORY_ID, categoryId);
		i.putExtra(EXTRA_KEY_WORD_SEARCH, keywordSearch);
		context.startActivity(i);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ia_product_list_view);
		mReturnCodeHandler = new InUIThreadHandler();
		mBuiltinServiceManager = BuiltinServiceManager.getInstance(ProductsActivity.this);
		builtservice = mBuiltinServiceManager.getBuitinService();
		Action = getIntent().getAction();
		extras = getIntent().getExtras();
		mArea = IAManager.getInstance(this).getMyArea();
		mQuery = new AQuery(this);
		initUIComponent();
		if (Action.equals(ACTION_PRODUCT_SEARCH_GLOBAL_BY_KEY)){
			keyWord = extras.getString(EXTRA_KEY_WORD_SEARCH);
			getData(keyWord);
		}else if (Action.equals(ACTION_PRODUCT_SEARCH_GLOBAL)){

		}else if (Action.equals(ACTION_PRODUCT_CATEGORY_SEARCH)){
			keyWord = extras.getString(EXTRA_KEY_WORD_SEARCH);
			CategoryId = extras.getString(EXTRA_CATEGORY_ID);
			getDatebyCategory(keyWord);
		}
	}

	private void initUIComponent(){
		btnBack = (ImageButton)findViewById(R.id.btn_title_na_menu);
		btnHome = (ImageButton)findViewById(R.id.btn_title_logo_home);
		btnSearch = (ImageView)findViewById(R.id.btn_title_search_home);
		btnBack.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.icon_back));
		btnSearch.setVisibility(View.GONE);
		edt_search = (EditText)findViewById(R.id.et_search);
		mLisview = (PullToRefreshListView)findViewById(R.id.product_list);
		mLisview.setMode(Mode.BOTH);
		//		mAdapter = new ProductsAdapter(this, mList);
		mAdapter= new AdapterProductViewAll(this, mList,mQuery);
		mLisview.setAdapter(mAdapter); 
		mAdapter.notifyDataSetChanged();
		mBar = (ProgressBar)findViewById(R.id.pb_loading);
		btnBack.setOnClickListener(this);
		btnHome.setOnClickListener(this);
		mLisview.setOnRefreshListener(this);
		mBar.setVisibility(View.GONE);
		edt_search.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
					keyWord = edt_search.getText().toString();
					PageNumber = 1;
					if (Action.equals(ACTION_PRODUCT_CATEGORY_SEARCH)){
						getDatebyCategory(keyWord);
					}else {
						CategoryId = null;
						getData(keyWord);
					}
				}
				return false;
			}
		});
	}

	private void getData(String key){
		edt_search.setText(keyWord);
		mList.clear();
		mAdapter.notifyDataSetChanged();
		ClassifiedCore.getInstance(this).taskGetSearchGlobal(mListener, mArea.getRemoteId(), ISDISABLE, CategoryType, PAGELIMIT, PageNumber, key,null);
		mBar.setVisibility(View.VISIBLE);
	}

	private void getDatebyCategory(String keysearch){
		edt_search.setText(keyWord);
		mList.clear();
		mAdapter.notifyDataSetChanged();
		ClassifiedCore.getInstance(this).taskGetSearchGlobal(mListener, mArea.getRemoteId(), ISDISABLE, CategoryType, PAGELIMIT, PageNumber, keysearch,CategoryId);
		mBar.setVisibility(View.VISIBLE);
	}

	class ViewHandler {
		public void showMessageToast(final String message) {
			Toast.makeText(ProductsActivity.this, message, Toast.LENGTH_SHORT)
			.show();
		}

		public void showNetworkErrorToast() {
			String message = getString(R.string.msg_connection_timeout);
			StatusMessageUtil.getInstance(ProductsActivity.this)
			.showCustomWarningToast(ProductsActivity.this, message, 0);
		}

		public void showRelogonAlertDialog() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					ProductsActivity.this)
			.setTitle(R.string.logon_dialog_alert_title)
			.setMessage(
					getResources()
					.getString(
							R.string.msg_session_duplicate_message,
							getResources().getString(R.string.app_name))).setPositiveButton(R.string.text_login,new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,int which) {
									BuiltinServiceManager.getInstance(ProductsActivity.this).getBuitinService();
								}
							})
							.setNegativeButton(R.string.text_cancel,new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,int which) {
									dialog.cancel();
								}
							});
			builder.create().show();
		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

	}

	class SearchListener extends ClassifiedListener {
		@Override
		public void finishGetGlobalSearch(final int returnCode,
				final ArrayList<ListItemEntity> items, boolean hasMore, final int pageCount) {
			// TODO Auto-generated method stub
			super.finishGetGlobalSearch(returnCode, items, hasMore, pageCount);
			runOnUiThread(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					if (returnCode == IProtocol.STATUS_CODE_OK_200 && items != null){
						if ( PageNumber < pageCount){
							PageNumber +=1;
						}else{
							PageNumber = -1;
						}
						mList.addAll(items);
						mAdapter.notifyDataSetChanged();

					}
					mLisview.onRefreshComplete();
					mBar.setVisibility(View.GONE);

				}
			});
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_title_na_menu:
			ProductsActivity.this.finish();
			break;
		case R.id.btn_title_logo_home:
			HomeClassifeldActivity.actionLaunch(this);
			break;
		default:
			break;
		}
	}
	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		// TODO Auto-generated method stub
		if (PageNumber > 0){
			if (refreshView.getCurrentMode() == Mode.PULL_FROM_START){
				PageNumber = 1;
				mList.clear();
				mAdapter.notifyDataSetChanged();
			}
			ClassifiedCore.getInstance(this).taskGetSearchGlobal(mListener, mArea.getRemoteId(), ISDISABLE, CategoryType, PAGELIMIT, PageNumber, keyWord,CategoryId);
		}else{
			new Handler().post(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					mLisview.onRefreshComplete();	
				}
			});
		}
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(isTaskRoot()){

			long triggerSize = 3000000; 
			long targetSize = 2000000;      
			AQUtility.cleanCacheAsync(this, triggerSize, targetSize);
		}
	}


}
